<template>
  <div>
    <h1>{{this.message}}</h1>

    <hr>
    <h1>{{this.ruleForm}}</h1>
    <hr>
    <h1>    {{websocket}}
    </h1>

    <el-form :model="ruleForm"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="上线名字" prop="nickname">
        <el-input v-model="ruleForm.nickname"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="toLogin">上线</el-button>
      </el-form-item>
    </el-form>

    <label for="content">输入内容：</label>
    <input type="text" id="content" v-model="content">
    <label for="target">发送人名称：</label>
    <input type="text" id="target" v-model="target">
<!--    <el-item label="发送人名称" prop="nickname">-->
<!--        <el-input v-model="target"></el-input>-->
<!--      </el-item>-->
<!--    <el-item label="消息内容" prop="nickname">-->
<!--        <el-input v-model="content"></el-input>-->
<!--      </el-item>-->

        <el-button @click="sendMessage(1)">发送信息</el-button>
    <!-- 你的组件模板 -->
  </div>
</template>

<script>
export default {
  name: "Inquiry",
  data() {
    return {
      type:'',
      //接收对象
      target:'',
      /**
       * 消息
       */
      content:'',
      message:{},
      ruleForm:{
        nickname: '', // 这里应该是你从某个地方（比如Vuex, props等）获取的用户昵称
        ws_address: 'ws://localhost:9401', // WebSocket服务器地址
      },
      websocket: null,
    };
  },
  created() {
    this.initializeWebSocket();
  },
  methods: {
    initializeWebSocket() {
      this.websocket = new WebSocket(this.ruleForm.ws_address);
      this.websocket.onopen = (event) => {
        console.log('WebSocket连接已打开');
        // this.sendMessage(); // 连接打开后，可以立即发送一个消息
      };

      this.websocket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        this.message=data;
        console.log('从服务器接收到的消息:', data);
        // 在这里处理从服务器接收到的消息
      };

      this.websocket.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };

      this.websocket.onclose = (event) => {
        console.log('WebSocket连接已关闭');
        // 可以选择重新连接或进行其他操作
      };
    },
    toLogin() {
      if (this.websocket.readyState === WebSocket.OPEN) {
        const message = JSON.stringify({
          code: '10001',
          nickname: this.ruleForm.nickname
        });
        this.websocket.send(message);
      } else {
        console.log('WebSocket连接未打开，无法发送消息');
      }
    },
    beforeDestroy() {
      if (this.websocket) {
        this.websocket.close(); // 在组件销毁前关闭WebSocket连接
      }
    },
    //发送信息
    sendMessage(type){
      if (this.websocket.readyState === WebSocket.OPEN) {
        const message = JSON.stringify({
          code: '10002',
          target: this.target,
          content:this.content,
          nickname:this.ruleForm.nickname,
          type: type
        });
        this.websocket.send(message);
      } else {
        console.log('WebSocket连接未打开，无法发送消息');
      }
    }
  }
};
</script>




